"""
数据源数据模型
"""
from datetime import datetime
from typing import Optional
from sqlalchemy import (
    Column, Integer, String, Boolean, DateTime, Text, 
    JSON, ForeignKey, Enum as SQLEnum
)
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
import enum

from app.core.database import Base


class DataSourceType(str, enum.Enum):
    """数据源类型枚举"""
    MQTT = "mqtt"
    HTTP_API = "http_api"
    COAP = "coap"
    WEBSOCKET = "websocket"
    DATABASE = "database"
    FILE_UPLOAD = "file_upload"
    STREAMING = "streaming"


class DataSourceStatus(str, enum.Enum):
    """数据源状态枚举"""
    CONNECTED = "connected"
    DISCONNECTED = "disconnected"
    ERROR = "error"
    TESTING = "testing"


class DataFormat(str, enum.Enum):
    """数据格式枚举"""
    JSON = "json"
    CSV = "csv"
    XML = "xml"
    BINARY = "binary"
    TEXT = "text"


class DataSource(Base):
    """数据源模型"""
    __tablename__ = "data_sources"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False, index=True)
    description = Column(Text, nullable=True)
    source_type = Column(SQLEnum(DataSourceType), nullable=False)
    data_format = Column(SQLEnum(DataFormat), default=DataFormat.JSON, nullable=False)
    status = Column(SQLEnum(DataSourceStatus), default=DataSourceStatus.DISCONNECTED, nullable=False)
    
    # 连接配置
    connection_config = Column(JSON, default=dict, nullable=False)  # 连接参数
    auth_config = Column(JSON, default=dict, nullable=False)  # 认证配置
    data_schema = Column(JSON, default=dict, nullable=False)  # 数据模式定义
    
    # 数据处理配置
    preprocessing_config = Column(JSON, default=dict, nullable=False)  # 预处理配置
    validation_rules = Column(JSON, default=list, nullable=False)  # 数据验证规则
    sampling_config = Column(JSON, default=dict, nullable=False)  # 采样配置
    
    # 状态信息
    is_active = Column(Boolean, default=True, nullable=False)
    last_connected = Column(DateTime(timezone=True), nullable=True)
    last_data_received = Column(DateTime(timezone=True), nullable=True)
    error_message = Column(Text, nullable=True)
    
    # 统计信息
    total_records = Column(Integer, default=0, nullable=False)
    last_24h_records = Column(Integer, default=0, nullable=False)
    data_quality_score = Column(Integer, default=0, nullable=False)  # 0-100
    
    # 关联关系
    project_id = Column(Integer, ForeignKey("projects.id"), nullable=False)
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False)
    
    # 关系
    project = relationship("Project", back_populates="data_sources")
    
    def __repr__(self):
        return f"<DataSource(id={self.id}, name='{self.name}', type='{self.source_type}')>"